<template>
    <div class="addproduct">
        <el-steps :active="active" finish-status="success" align-center>
            <el-step title="填写商品信息" />
            <el-step title="填写商品促销" />
            <el-step title="填写商品属性" />
            <el-step title="选择商品关联" />
        </el-steps>
        <!-- 页面1 -->
        <div class="pro-info item" v-show="active === 0">
            <el-form label-width="150px" ref="infoFormRef" :rules="infoRules" :model="params">
                <el-form-item label="商品分类:" prop="productCategoryId">
                    <el-cascader :options="proCategories" :props="props1" clearable
                        v-model="params.productCategoryId" />
                </el-form-item>
                <el-form-item label="商品名称:" prop="name">
                    <el-input v-model="params.name"></el-input>
                </el-form-item>
                <el-form-item label="副标题:" prop="subTitle">
                    <el-input v-model="params.subTitle"></el-input>
                </el-form-item>
                <el-form-item label="商品品牌:" prop="brandId">
                    <el-select class="m-2" placeholder="请选择品牌" size="large" v-model="params.brandId"
                        @change="getBrandFn">
                        <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品货号:" prop="productSn">
                    <el-input type="textarea" placeholder="请输入内容" v-model="params.productSn"></el-input>
                </el-form-item>
                <el-form-item label="商品售价:" prop="originalPrice">
                    <el-input v-model="params.originalPrice"></el-input>
                </el-form-item>
                <el-form-item label="市场价:" prop="price">
                    <el-input v-model="params.price"></el-input>
                </el-form-item>
                <el-form-item label="商品库存:" prop="stock">
                    <el-input v-model="params.stock"></el-input>
                </el-form-item>
                <el-form-item label="计量单位:" prop="unit">
                    <el-input v-model="params.unit"></el-input>
                </el-form-item>
                <el-form-item label="商品重量:" prop="weight">
                    <el-input :input-style="{ width: 200 + 'px' }" v-model="params.weight"></el-input>
                    <span style="margin-left:50px">克</span>
                </el-form-item>
                <el-form-item label="排序:" prop="sort">
                    <el-input v-model="params.sort"></el-input>
                </el-form-item>
            </el-form>
            <el-button style="margin-top: 12px" @click="toSaleFormFn" type="primary">下一步，填写商品促销</el-button>
        </div>
        <!-- 页面2 -->
        <div class="pro-sale item" v-show="active === 1">
            <el-form label-width="150px" ref="saleFormRef" v-model="params">
                <el-form-item label="赠送积分:" prop="keyword">
                    <el-input v-model="params.giftPoint"></el-input>
                </el-form-item>
                <el-form-item label="赠送成长值:" prop="keyword">
                    <el-input v-model="params.giftGrowth"></el-input>
                </el-form-item>
                <el-form-item label="积分购买限制:" prop="keyword">
                    <el-input v-model="params.usePointLimit"></el-input>
                </el-form-item>
                <el-form-item label="预告商品:" prop="previewStatus">
                    <el-switch v-model="params.previewStatus" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="商品上架:" prop="publishStatus">
                    <el-switch v-model="params.publishStatus" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="商品推荐:" prop="newStatus">
                    <span>新品</span>
                    <el-switch v-model="params.newStatus" :active-value="1" :inactive-value="0"></el-switch>
                    <span>推荐</span>
                    <el-switch v-model="params.recommandStatus" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
                <el-form-item label="服务保证:">
                    <el-checkbox-group @change="changeService">
                        <el-checkbox label="无忧退货" name="type" />
                        <el-checkbox label="快速退款" name="type" />
                        <el-checkbox label="免费包邮" name="type" />
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="详细页标题:" prop="detailTitle">
                    <el-input v-model="params.detailTitle"></el-input>
                </el-form-item>
                <el-form-item label="详细页描述:" prop="detailDesc">
                    <el-input v-model="params.detailDesc"></el-input>
                </el-form-item>
                <el-form-item label="商品关键字:" prop="keywords">
                    <el-input v-model="params.keywords"></el-input>
                </el-form-item>
                <el-form-item label="商品备注:" prop="note">
                    <el-input type="textarea" v-model="params.note"></el-input>
                </el-form-item>
                <el-form-item label="选择优惠方式:" prop="keyword">
                    <el-tabs v-model="activeName" type="card" class="demo-tabs">
                        <el-tab-pane label="无优惠" name="first"></el-tab-pane>
                        <el-tab-pane label="特惠促销" name="second">
                            <el-form-item label="开始时间：">
                                <ElConfigProvider :locale="zhCn">
                                    <el-date-picker type="datetime" placeholder="选择开始时间"
                                        v-model="params.promotionStartTime" />
                                </ElConfigProvider>

                            </el-form-item>
                            <el-form-item label="结束时间：" class="middle">
                                <ElConfigProvider :locale="zhCn">
                                    <el-date-picker type="datetime" placeholder="选择结束时间"
                                        v-model="params.promotionEndTime" />
                                </ElConfigProvider>
                            </el-form-item>
                            <el-form-item label="促销价格：" placeholder="请输入促销价格">
                                <el-input width="120" :input-style="{ width: 196 + 'px' }"
                                    v-model="params.promotionPrice"></el-input>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="会员价格" name="third">
                            <el-form v-model="params.memberPriceList">
                                <el-form-item :label="`${member.memberLevelName}:`"
                                    v-for="member in params.memberPriceList" :key="member.memberLevelId">
                                    <el-input width="120" :input-style="{ width: 196 + 'px', marginBottom: 10 + 'px' }"
                                        v-model="member.memberPrice"></el-input>
                                </el-form-item>

                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="阶梯价格" name="fourth">
                            <el-table border :data="params.productLadderList">
                                <el-table-column label="数量" prop="count">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.count"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="折扣" prop="discount">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.discount"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button link type="primary" @click="delProductLadder(scope.row.id)">删除
                                        </el-button>
                                        <el-button link type="primary" @click="addProductLadder">添加</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="满减价格" name="fived">
                            <el-table border :data="params.productFullReductionList">
                                <el-table-column label="满">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.fullPrice"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="立减">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.reducePrice"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button link type="primary" @click="delProductFullReduction(scope.row.id)">删除
                                        </el-button>
                                        <el-button link type="primary" @click="addProductFullReduction">添加</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-form-item>

            </el-form>
            <el-button style="margin-top: 12px" @click="pre">上一步，填写商品信息</el-button>
            <el-button style="margin-top: 12px" @click="next" type="primary">下一步，填写商品属性</el-button>
        </div>
        <!-- 页面3 -->
        <div class="pro-attrs item" v-show="active === 2">
            <el-form label-width="150px" ref="attrFormRef" v-model="params">
                <el-form-item label="属性类型:" prop="proAttrId">
                    <el-select class="m-2" placeholder="请选择" size="large" @change="getAttrFn" v-model="proAttrId">
                        <el-option v-for="item in proAttrs" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品规格:">
                    <el-input></el-input>
                    <el-table :data="params.skuStockList" style="width: 100%;margin:20px 0" border>
                        <el-table-column prop="price" label="销售价格" />
                        <el-table-column prop="stock" label="商品库存" />
                        <el-table-column prop="lowStock" label="库存预警值" />
                        <el-table-column prop="skuCode" label="SKU编号" width="200" />
                        <el-table-column prop="address" label="操作">
                            <template #default>

                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary">刷新列表</el-button>
                    <el-button type="primary">同步价格</el-button>
                    <el-button type="primary">同步库存</el-button>
                </el-form-item>
                <el-form-item label="商品参数:">
                    <el-input></el-input>
                </el-form-item>
                <el-form-item label="商品相册:">
                    <el-upload action="http://120.24.64.5:8088/mall-admin/minio/upload" list-type="picture-card"
                        :on-success="handleSuccess" v-model:file-list="fileList" :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>

                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="规格参数:">
                    <el-tabs type="card" class="demo-tabs">
                        <el-tab-pane label="电脑端详情" name="first">电脑端</el-tab-pane>
                        <el-tab-pane label="移动端详情" name="second">Config</el-tab-pane>
                    </el-tabs>
                </el-form-item>
            </el-form>
            <el-button style="margin-top: 12px" @click="pre">上一步，填写商品促销</el-button>
            <el-button style="margin-top: 12px" @click="next" type="primary">下一步，填写商品关联</el-button>
        </div>
        <!-- 页面4 -->
        <div class="pro-relations item" v-show="active === 3">
            <el-form label-width="150px" ref="relationFormRef" v-model="params">
                <el-form-item label="关联专题:">
                    <ElConfigProvider :locale="zhCn">
                        <el-transfer filterable :filter-method="filterSubjectMethod" filter-placeholder="请输入专题名称"
                            :data="subjectsList" :titles="['待选择', '选择']" v-model="choeseSubjects" :props="{
                                key: 'id',
                                label: 'title',
                            }" @change="subjectChange" />
                    </ElConfigProvider>

                </el-form-item>
                <el-form-item label="关联优选:">
                    <ElConfigProvider :locale="zhCn">
                        <el-transfer v-model="chosePrefrences" filterable :filter-method="filterPrefrenceMethod"
                            filter-placeholder="请输入优选名称" :data="prefrenceAreaList" :titles="['待选择', '选择']" :props="{
                                key: 'id',
                                label: 'name',
                            }" @change="preferenceChange" />
                    </ElConfigProvider>
                </el-form-item>
            </el-form>
            <el-button style="margin-top: 12px" @click="pre">上一步，填写商品关联</el-button>
            <el-button style="margin-top: 12px" @click="submitProFn" type="primary">提交商品</el-button>
        </div>

    </div>
</template>
<script setup lang='ts'>
import { inject, reactive, ref, toRefs } from 'vue';
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { ElMessage, ElMessageBox, FormInstance, FormRules, ElConfigProvider, UploadFiles, UploadRequestOptions, UploadProps, UploadUserFile, } from 'element-plus';
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { pro } from '@/api'
import type { TabsPaneContext, UploadFile } from 'element-plus'
import { useRoute } from 'vue-router';
const route = useRoute()
interface Istate {
    productsList: IProductListModel[],
    total: number,
    brandList: IProBrandsModel[],
    proCategories: IProductCategoryWithChildrenModel[],
    proAttrs: IattributeListModel[],
    prefrenceAreaList: IPrefrenceAreaList[],
    subjectsList: ISubjectListAll[]
}
// 请求参数
const params = reactive<ICreateProductParams>({
    albumPics: "",
    brandId: '',
    brandName: "",
    deleteStatus: 0,
    description: "",
    detailDesc: "",
    detailHtml: "",
    detailMobileHtml: "",
    detailTitle: "",
    feightTemplateId: 0,
    giftGrowth: 0,
    giftPoint: 0,
    id: 0,
    keywords: "",
    lowStock: 0,
    memberPriceList: [],
    name: "",
    newStatus: 0,
    note: "",
    originalPrice: 0,
    pic: "",
    prefrenceAreaProductRelationList: [],
    previewStatus: 0,
    price: 0,
    productAttributeCategoryId: 0,
    productAttributeValueList: [],
    productCategoryId: 0,
    productCategoryName: "",
    productFullReductionList: [
        {
            fullPrice: 0,
            id: 0,
            productId: 0,
            reducePrice: 0,
        }
    ],
    productLadderList: [
        {
            count: 0,
            discount: 0,
            id: 0,
            price: 0,
            productId: 0,
        }
    ],
    productSn: "",
    promotionEndTime: "",
    promotionPerLimit: 0,
    promotionPrice: 0,
    promotionStartTime: "",
    promotionType: 0,
    publishStatus: 0,
    recommandStatus: 0,
    sale: 0,
    serviceIds: "",
    skuStockList: [
        {
            id: 0,
            lockStock: 0,
            lowStock: 0,
            pic: '',
            price: 0,
            productId: 0,
            promotionPrice: 0,
            sale: 0,
            skuCode: '',
            spData: '',
            stock: 0
        }
    ],
    sort: 0,
    stock: 0,
    subTitle: "",
    subjectProductRelationList: [],
    unit: "",
    usePointLimit: 0,
    verifyStatus: 0,
    weight: 0
})
// 请求返回的数据
const state = reactive<Istate>({
    productsList: [],
    total: 0,
    brandList: [],
    proCategories: [],
    proAttrs: [],
    prefrenceAreaList: [],
    subjectsList: []
})
const infoFormRef = ref<FormInstance>()
const saleFormRef = ref<FormInstance>()
const attrFormRef = ref<FormInstance>()
const relationFormRef = ref<FormInstance>()
const active = ref(0)//steps 跳转
const activeName = ref('first')//穿梭
const proAttrId = ref('')
let { brandList, proCategories, proAttrs, prefrenceAreaList, subjectsList } = toRefs(state);
// 编辑
if (route.query.id) {
    pro.getIDPproductproductUpdateInfoApi(parseInt(route.query.id as string)).then(res => {
        if (res.code === 200) {
            Object.assign(params, res.data)
        }
    })
}
// 请求  pro.getProductCategoryWithChildrenApi()
Promise.all([pro.getProBrandsApi({ pageNum: 1, pageSize: 100 }), pro.getProductCategoryWithChildrenApi(), pro.queryMemberLevelListApi(0), pro.queryPrefrenceAreaListApi(), pro.getProAttrsApi({ pageNum: 1, pageSize: 100 }), pro.querySubjectListAllApi()]).then(([brands, attrs, memberLevls, prefrenceArea, proAttrs, subjects]) => {
    if (brands.code === 200 && attrs.code === 200 && memberLevls.code === 200 && prefrenceArea.code === 200 && proAttrs.code === 200 && subjects.code === 200) {
        state.brandList = brands.data.list;
        state.proCategories = attrs.data;
        // 处理会员
        params.memberPriceList = memberLevls.data.map(item => ({ memberLevelId: item.id, memberLevelName: item.name, id: 0, productId: 0, memberPrice: 0 }));
        state.proAttrs = proAttrs.data.list;
        state.prefrenceAreaList = prefrenceArea.data
        state.subjectsList = subjects.data
    }
}).catch(err => {
    console.log(err);
})
// 页面1 :
// 级联 商品分类数据格式
const props1 = {
    checkStrictly: true,
    value: 'id',
    label: 'name',
    children: 'children',
    emitPath: false
}
// 校验 type: 'array'
const infoRules = reactive<FormRules>({
    productCategoryId: [
        { required: true, message: '请选择商品分类', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' },
    ],
    subTitle: [
        { required: true, message: '请输入商品副标题', trigger: 'blur' }
    ],
    brandId: [
        { required: true, message: '请选择商品品牌', trigger: 'change' }
    ],
})

// 去营销页
const toSaleFormFn = () => {
    infoFormRef.value?.validate((valid: boolean) => {
        if (valid) {
            active.value++;
        } else {
            ElMessage.error('验证失败')
            return false;
        }
    })
}

// 取品牌
const getBrandFn = (val: number) => {
    let idx = state.brandList.findIndex(item => item.id === val)
    params.brandName = state.brandList[idx].name
}

// 页面2 :
// 阶梯价格  添加
const addProductLadder = () => {
    params.productLadderList.push({
        count: 0,
        discount: 0,
        id: 0,
        price: 0,
        productId: 0,
    })
}
// 阶梯价格 删除
const delProductLadder = (id: number) => {
    if (params.productLadderList.length <= 1) return;
    let idx = params.productLadderList.findIndex(item => item.id === id)
    params.productLadderList.splice(idx, 1)
}
// 满减 添加
const addProductFullReduction = () => {
    params.productFullReductionList.push({
        fullPrice: 0,
        id: 0,
        productId: 0,
        reducePrice: 0,
    })
}
// 满减 删除
const delProductFullReduction = (id: number) => {
    if (params.productFullReductionList.length <= 1) return;
    let idx = params.productFullReductionList.findIndex(item => item.id === id);
    params.productFullReductionList.splice(idx, 1)
}
// 服务保证
const changeService = (val: any) => {
    console.log('service', val);
}

// 页面3 
// 获取属性
const getAttrFn = (id: number) => {
    let idx = state.proAttrs.findIndex(item => item.id === id)
    params.productAttributeValueList.push({
        productAttributeId: id,
        value: state.proAttrs[idx].name,
        id: 0,
        productId: 0
    })
}
// 图片上传
const fileList = ref<UploadUserFile[]>()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    // console.log(uploadFile, uploadFiles)
    fileList.value = []
    dialogImageUrl.value = ''
    dialogVisible.value = false
    params.pic = ''
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    console.log('上传商品图片', response, uploadFile);
    fileList.value = []
    fileList.value.push(response.data)
    params.pic = response.data.url
}

// 页面4
// 穿梭
const chosePrefrences = ref([])
const choeseSubjects = ref([])
// 查询
const filterPrefrenceMethod = (query: string, item: IPrefrenceAreaList) => {
    return item.name.includes(query)
}
const filterSubjectMethod = (query: string, item: ISubjectListAll) => {
    return item.title.includes(query)
}
// 选中 拿id
const subjectChange = (key: number[], direction: string, val: number) => {
    params.subjectProductRelationList = key.map(id => ({
        id: 0,
        productId: 0,
        subjectId: id
    }))

}
const preferenceChange = (key: number[], direction: string, val: number) => {
    params.prefrenceAreaProductRelationList = key.map(id => ({
        id: 0,
        productId: 0,
        prefrenceAreaId: id
    }))
}
// 提交
const submitProFn = () => {
    ElMessageBox.confirm(
        '是否添加该商品?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        if (route.query.id) {
            pro.updateIDPproductproductUpdateInfoApi(parseInt(route.query.id as string), params).then(res => {
                if (res.code === 200) {
                    ElMessage.success('修改成功');
                    active.value = 0;
                    infoFormRef.value?.resetFields()
                    // 组件重载
                    const toggle: () => void = inject('reload') as () => void;
                    toggle();
                }
            })
        } else {
            pro.createProductApi(params).then((res) => {
                if (res.code === 200) {
                    ElMessage.success('添加成功');
                    active.value = 0;
                    infoFormRef.value?.resetFields()
                    // 组件重载
                    const toggle: () => void = inject('reload') as () => void;
                    toggle();
                }
            })
        }

    })
}

// 上一步
const pre = () => {
    if (active.value-- <= 0) active.value = 0
}
// 下一步
const next = () => {
    if (active.value++ > 2) active.value = 3;

}
</script>
<style lang="less" scoped>
.addproduct {
    padding: 30px;
    border: 1px solid #000;
    text-align: center;

    .item {
        width: 780px;
    }

    .el-steps {
        margin-bottom: 40px;
    }

    .pro-sale {
        .middle {
            margin: 20px 0;
        }
    }
}
</style>